package com.mo.lib.utils.file

import android.Manifest.permission
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import androidx.annotation.RequiresPermission
import java.lang.IllegalArgumentException

/**
 * @ author：mo
 * @ data：2022/4/25:9:59
 * @ 功能：
 */

/**根据uri获取文件的绝对路径，解决Android 4.4以上 根据uri获取路径的方法 */
@RequiresPermission(permission.READ_MEDIA_IMAGES)
fun Context.getFilePathByUri(uri: Uri?): String? {
    if (uri == null) return null
    var path: String? = null
    val scheme = uri.scheme // 以 file:// 开头的
    if (ContentResolver.SCHEME_FILE == scheme) {
        path = uri.path
        return path
    } // 以 content:// 开头的，比如 content://media/extenral/images/media/17766
    if (ContentResolver.SCHEME_CONTENT == scheme && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        val cursor = contentResolver.query(uri, arrayOf(MediaStore.Images.Media.DATA), null, null, null)
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                if (columnIndex > -1) {
                    path = cursor.getString(columnIndex)
                }
            }
            cursor.close()
        }
        return path
    }

    // 4.4及之后的 是以 content:// 开头的，比如 content://com.android.providers.media.documents/document/image%3A235700
    if (ContentResolver.SCHEME_CONTENT == scheme && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(this, uri)) {
        if (isExternalStorageDocument(uri)) {
            val docId = DocumentsContract.getDocumentId(uri)
            val split = docId.split(":".toRegex()).toTypedArray()
            val type = split[0]
            if ("primary".equals(type, ignoreCase = true)) {
                return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
            }
        } else if (isDownloadsDocument(uri)) {
            val id = DocumentsContract.getDocumentId(uri)
            val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id))
            return getDataColumn( contentUri, null, null)
        } else if (isMediaDocument(uri)) {
            val docId = DocumentsContract.getDocumentId(uri)
            val split = docId.split(":".toRegex()).toTypedArray()
            val type = split[0]
            var contentUri: Uri? = null
            if ("image" == type) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            } else if ("video" == type) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
            } else if ("audio" == type) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
            }
            val selection = MediaStore.Images.Media._ID + "=?"
            val selectionArgs = arrayOf(split[1])
            return getDataColumn( contentUri, selection, selectionArgs)
        }
    } // MediaStore (and general)
    else if ("content".equals(scheme, ignoreCase = true)) { // Return the remote address
        if (isGooglePhotosUri(uri)) {
            return uri.lastPathSegment
        } else if (isHuaWeiUri(uri)) {
            val uriPath = uri.path //content://com.huawei.hidisk.fileprovider/root/storage/emulated/0/Android/data/com.xxx.xxx/
            if (uriPath != null && uriPath.startsWith("/root")) {
                return uriPath.replace("/root".toRegex(), "")
            }
        }
        return getDataColumn( uri, null, null)
    } else if ("file".equals(scheme, ignoreCase = true)) {
        return uri.path
    }
    return null
}

fun Context.getDataColumn(uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? {
    var cursor: Cursor? = null
    val column = MediaStore.Images.Media.DATA
    val projection = arrayOf(column)
    try {
        cursor = contentResolver.query(uri!!, projection, selection, selectionArgs, null)
        if (cursor != null && cursor.moveToFirst()) {
            val index = cursor.getColumnIndexOrThrow(column)
            return cursor.getString(index)
        }
    } catch (e: IllegalArgumentException) {
        e.printStackTrace()
    } finally {
        cursor?.close()
    }
    return null
}

/** 是否是外部存储文件资源*/
fun isExternalStorageDocument(uri: Uri)= "com.android.externalstorage.documents" == uri.authority

/** 是否是下载文件资源*/
fun isDownloadsDocument(uri: Uri)= "com.android.providers.downloads.documents" == uri.authority

/** 是否是媒体资源*/
fun isMediaDocument(uri: Uri)= "com.android.providers.media.documents" == uri.authority

/** 是否是谷歌相册资源*/
fun isGooglePhotosUri(uri: Uri)= "com.google.android.apps.photos.content" == uri.authority

/**是否是华为资源    content://com.huawei.hidisk.fileprovider/root/storage/emulated/0/Android/data/com.xxx.xxx/ */
fun isHuaWeiUri(uri: Uri)= "com.huawei.hidisk.fileprovider" == uri.authority
